package com.javasm.crm.service.sell.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.javasm.crm.domin.entity.sell.RepositorySellReturnOrder;
import com.javasm.crm.mapper.sell.RepositorySellReturnOrderMapper;
import com.javasm.crm.service.sell.IRepositorySellReturnOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author lqz
 * @since 2021-07-16
 */
@Service
@Transactional
public class RepositorySellReturnOrderServiceImpl extends ServiceImpl<RepositorySellReturnOrderMapper, RepositorySellReturnOrder> implements IRepositorySellReturnOrderService {

    @Autowired
    RepositorySellReturnOrderMapper repositorySellReturnOrderMapper;

    @Override
    public RepositorySellReturnOrder searchOne(QueryWrapper<RepositorySellReturnOrder> wrapper) {
        return repositorySellReturnOrderMapper.selectOne(wrapper);
    }

    @Override
    public boolean addOne(RepositorySellReturnOrder repositorySellReturnOrder) {
        //查找退货单号
        List<String> sellReturnCodeList = repositorySellReturnOrderMapper.selectSellReturnCodeList();
        if (sellReturnCodeList != null && !sellReturnCodeList.isEmpty()){
            ArrayList<Integer> integers = new ArrayList<>();
            for (String sellReturnCode : sellReturnCodeList) {
                String substring = sellReturnCode.substring(2);
                Integer integerReturnCode = Integer.valueOf(substring);
                integers.add(integerReturnCode);
            }
            //找到integers中的最大值
            Integer maxNum = 0;
            for (Integer integer : integers) {
                if (maxNum < integer){
                    maxNum = integer;
                }
            }
            //找到的最大值+1
            Integer num = Integer.valueOf(++maxNum);
            //转成字符串
            String numStr = num.toString();
            //声明一个字符串，用来合成数字部分
            String theNum = "";
            //数字不满4位数，在之前添加几个0
            if (numStr.length() < 4){
                int size = 4 - numStr.length();
                for (int i = 0; i < size; i++) {
                    theNum += "0";
                }
            }
            theNum += numStr;
            //合成退货单号
            String sellReturnCode = "TH" + theNum;
            repositorySellReturnOrder.setSellReturnCode(sellReturnCode);
        }else {
            repositorySellReturnOrder.setSellReturnCode("TH0001");
        }
        repositorySellReturnOrder.setSellReturnCreateTime(LocalDateTime.now());
        return repositorySellReturnOrderMapper.insert(repositorySellReturnOrder) > 0;
    }
}
